<?php

namespace app\admin\controller\share;

use app\admin\model\Change;
use app\admin\model\share\ShareUser;
use think\Db;
use app\common\controller\Backend;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\model\User as FUser;
use think\Validate;
use app\common\library\Auth;
use app\common\model\UserChangeLog;
use app\common\model\ShareUserRoleLog;
use app\common\model\ShareConfig;
use fast\Arr;

/**
 * 分销用户
 *
 * @icon fa fa-circle-o
 */
class Usert extends Backend
{

    /**
     * User模型对象
     * @var \app\admin\model\share\ShareUser
     */
    protected $relationSearch = true;
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\share\ShareUser;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with('user')
                ->where($where)
                ->where("staff",2)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $key => &$row) {
                $row->visible(['id', 'user_id', 'role', 'role_url', 'role1', 'role2', 'role3', 'role_type', 'addtime', 'parent_id', 'inviter_id', 'price', 'total_price', 'user.username', 'user.nickname', 'user.mobile', 'user.invitecode', 'score', 'amount']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $users = FUser::get($row['user_id']);
        $row['mobile'] = $users['mobile'];
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            if ($params['mobile'] != $users['mobile'] && FUser::getByMobile($params['mobile'])) {
                exception('手机号已存在');
                return false;
            }

            if ($row['user_flags']) {
                exception('已独立分割，不能再分割' . $row['user_flags']);
                return false;
            }

            if ($params['is_sep_income'] == 1) {
                if ($row['role'] < 5) {
                    exception('银牌经销商以下用户不可设置分隔收益');
                }

                $user_flag = \app\common\model\User::user_flags();
                $userinfo = \db('share_user')->where(['user_id' => $row['user_id']])->find();

                if (empty($row['user_flags'])) {
                    $row['user_flags'] = $user_flag;
                }
            }

            if ($params['mobile'] != $users['mobile']) {
                if (!Validate::regex($params['mobile'], "^1\d{10}$")) {
                    exception('手机号填写错误');
                }
                $before_mobile = $params['mobile'];
                $users->username = $params['mobile'];
                $users->mobile = $params['mobile'];
                $users->save();
                UserChangeLog::create(['user_id' => $users->id, 'before_mobile' => $before_mobile, 'after_mobile' => $params['mobile'], 'memo' => '后台操作变更手机号']);
            }

            if ((int)$params['role'] < (int)$row['role']) {
                exception('级别不能降低');
                return false;
            }
            if ((int)$params['role'] > (int)$row['role']) {
                $ShareConfig = ShareConfig::where(['role' => $params['role'], 'type' => 2])->find();
                $amount = empty($ShareConfig) ? $row['amount'] : $ShareConfig['reward'];
                $amount = ($row['amount'] > $amount) ? $row['amount'] : $amount;
                $params['amount'] = $amount;
                //变更级别记录日志
                ShareUserRoleLog::create(['user_id' => $row['user_id'], 'before_role' => $row['role'], 'after_role' => $params['role'], 'before_amount' => $row['amount'], 'after_amount' => $amount, 'memo' => '后台操作变更级别']);
            }

            $result = $row->allowField(true)->save($params);

            //设置独立分割
            if ($row['user_flags']) {
                $user_flags = Db::name('share_user_flags')->where('user_id', $row['user_id'])->find();
                if ($user_flags) exception('已被大团队分割，不能再分割');

                $this->setSepTeamUser($row['user_id'], $row['user_flags']);
            }

            // 升级分销商
            $this->model->promotion_save($row['parent_id'], $params['role'], $row['role_type']);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function change($ids = null)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            $user_id = $row['user_id'];

            $params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $mobile = $params['mobile'];
            $model = new Change();
            $pa_count = Db::name("share_user")->where(['parent_id' => $user_id])->count();
            if ($pa_count >= 3) {
                $this->error(__('手动设置用户下级已满'));
            }
            $id = DB::name('user')->where('mobile', $mobile)->value('id');
            if (!$id) {
                $this->error("手机号不存在");
            }
//            $down = Db::name("share_user")->where('parent_id', $id)->count();
//            if($down){
//                $this->error("此用户有下级节点 不可转移");
//            }
            $old_id = Db::name("share_user")->where('user_id', $id)->value('parent_id');
//            $inviter_id = Db::name("share_user")->where('user_id', $id)->value('inviter_id');
            $new_id = $user_id;
            $user_id = $id;
            $new_info = Db::name("share_user")->where(['user_id' => $new_id])->find();
//            $new_arr = Db::name("share_user")->where(['user_id' => $new_id])->value('role_url');
//            $new_arr = explode('/',trim($new_arr,'/'));
//            $new_arr[] = $new_id;
//            if(!in_array($inviter_id,$new_arr)){
//                $this->error("此路径不可转移");
//            }
            if ($new_id == $old_id) {
                $this->error("当前节点不需要改变");
            }
            if ($new_id == $user_id) {
                $this->error("不可以自己做自己节点");
            }
            $Share = new ShareUser();
            // $get_parent = $Share->get_parent_id($new_id);//原方法 判断节点是否满员
            // $get_parent_id = empty($get_parent) ?  0 : $get_parent[0];
            // $role_type = empty($get_parent) ?  0 : $get_parent[1];
            // if ($get_parent_id  == 0) {
            //     $this->error("邀请码已满额");
            // }
            $list = Db::name("share_user")->where(['parent_id' => $new_id])->select();
            foreach ($list as $k => $v) {
                Db::name("share_user")->where('user_id', $v['user_id'])->update(['role_type' => $k]);
            }
            $temp_data['pid'] = $new_id;
            $temp_data['parent_user_id'] = $new_id;
            $temp_data['role_type'] = count($list) + 1;
            $role_type = $temp_data['role_type'];
            // role_url
            $role = $new_info['role'];

            Db::name("share_user")->where('user_id', $user_id)->update(['parent_id' => $new_id, 'inviter_id' => $new_id, 'role_type' => $role_type]);
            DB::name('user')->where('mobile', $mobile)->update($temp_data);


            $all_node = [$user_id];
            $this->user_in([$user_id], $all_node);
            $all_node = array_unique($all_node);
            $list = Db::name("share_user")->where('user_id', 'in', implode(',', $all_node))->select();
            $old_url = Db::name("share_user")->where('user_id', $user_id)->value('role_url');
            $new_url = Db::name("share_user")->where('user_id', $new_id)->value('role_url');
            $new_url = '/' . $new_id . $new_url;
            foreach ($list as $v) {
                $v['role_url'] = str_replace($old_url, $new_url, $v['role_url']);
                Db::name("share_user")->where('user_id', $v['user_id'])->update(['role_url' => $v['role_url']]);
            }

            model('\app\admin\model\share\ShareUser')->setTeamUser($old_id, $new_id);

            (new ShareUser())->promotion_save($new_id, $role, $role_type);
            $old_role_url = $row['role_url'];
            $model->save(compact('user_id', 'old_id', 'new_id', 'old_role_url'));
            $this->success("操作成功");
        }
        return $this->view->fetch();
    }

    protected function user_in($pids, &$add_data_all)
    {
        $where['parent_id'] = ['in', $pids];
        $ut_data = Db::name('share_user')->where($where)->field("user_id")->select();
        $count = count($ut_data);
        $pids = array_column($ut_data, 'user_id');
        if (count($pids) > 0) {
            $add_data_all = array_merge($add_data_all, $pids);

            self::user_in($pids, $add_data_all);
        }
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public
    function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $row = $this->model->get($ids);

        $this->userinfo_del($row['id']);
        $this->success();
    }

    public function userinfo_del($pid)
    {
        $share_user = Db::name('share_user')->where(['id' => $pid])->find();
        if (!empty($share_user)) {
            $share_user['shareuserid'] = $share_user['id'];
            unset($share_user['id']);
            $share_user_insert = Db::name("share_user_delete")->strict(false)->insert($share_user);
            if (!$share_user_insert) {
                $this->error(__("添加失败"));
            }
            $share_user_delete = Db::name('share_user')->where(['id' => $share_user['shareuserid']])->delete();
            Db::name('share_user_flags')->where(['user_id' => $share_user['shareuserid']])->delete();
            if (!$share_user_delete) {
                $this->error(__("删除失败"));
            }
        }

        $user = Db::name('user')->where(['id' => $share_user['user_id']])->find();
        if (!empty($user)) {
            $user['uid'] = $user['id'];
            unset($user['id']);
            $user_insert = Db::name("user_delete")->strict(false)->insert($user);
            if (!$user_insert) {
                $this->error(__("添加失败"));
            }
            Auth::instance()->delete($user['uid']);
//            $user_delete = Db::name('user')->where(['id' => $user['uid']])->delete();
//            if (!$user_delete) {
//                $this->error(__("删除失败"));
//            }
        }

        $where['parent_id'] = ['in', $share_user['user_id']];
        $share_users = Db::name('share_user')->where($where)->select();
        if ($share_users) {
            foreach ($share_users as $item) {
                $this->userinfo_del($item['id']);
            }
        }
        return true;
    }

    /**
     * 详情
     */
    public
    function detail($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $user = FUser::get($row['user_id']);

        $share_user = Db::name("share_user")->where(['user_id' => $row['user_id']])->find();
        $parent_user = Db::name("share_user")->where(['user_id' => $row['parent_id']])->find();
        $flags = Db::name("share_user_flags")->where(['user_id' => $row['user_id']])->find();

        $user_parent = FUser::get($row['parent_id']);
        $row->nickname = empty($user) ? '无' : $user['nickname'];
        $row->mobile = empty($user) ? '无' : $user['mobile'];
        $row->parent_mobile = empty($user_parent) ? '无' : $user_parent['mobile'];
        $row->parent_nickname = empty($user_parent) ? '无' : $user_parent['nickname'];
        $row->parent_role = empty($parent_user) ? '无' : $parent_user['role'];
        $row->is_sep_income = empty($share_user) ? '无' : $share_user['is_sep_income'];
        $row->user_flags = empty($flags) ? '无' : $flags['user_flags'];
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public
    function pwd($ids)
    {
        $pwd = $this->getEncryptPassword("123456", 123456);
        exit;
        $save_status = Db::name("user")->where(['user_id' => $ids])->update(['password' => $pwd, 'salt' => 123456]);
        if ($save_status) {
            $this->error(__("密码重置成功"));
        } else {
            $this->error(__("密码重置失败"));
        }
    }

    public
    function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    public
    function resetpwd($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $user = FUser::get($row['user_id']);
        $salt = \fast\Random::alnum();
        $user->password = \app\common\library\Auth::instance()->getEncryptPassword('123456', $salt);
        $user->salt = $salt;
        $res = $user->save();
        if ($res) {
            $this->error(__("密码重置成功"));
        } else {
            $this->error(__("密码重置失败"));
        }
    }

    public function addchange($ids = null)
    {
        $params = $this->request->post('row/a');
        if ($params['mobile']) {
            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            $user_id = $row['user_id'];

            $params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $mobile = $params['mobile'];
            $nickname = $params['nickname'];

            //判断节点是否已满 sxc 10-29
            $Share = new ShareUser();
            $get_parent = $Share->get_parent_id($user_id);//原方法 判断节点是否满员
            $get_parent_id = empty($get_parent) ? 0 : $get_parent[0];
            $role_type = empty($get_parent) ? 0 : $get_parent[1];
            if ($get_parent_id == 0) {
                $this->error("邀请码已满额");
            }

            $id = DB::name('user')->where('mobile', $mobile)->value('id');
            if ($id) {
                $this->error("手机号已存在");
            }
            $uin_add['nickname'] = $nickname;
            $uin_add['mobile'] = $mobile;
            $uin_add['username'] = $mobile;
            $uin_add['pid'] = $user_id;
            $uin_add['password'] = '5f1d7a84db00d2fce00b31a7fc73224f';
            $uin_add['salt'] = '123456';
            $uin_add['status'] = 'normal';

            //此处需要给出所在部门
            $temp_data['invitecode'] = $mobile;
            $temp_data['pid'] = $get_parent_id;
            $temp_data['parent_user_id'] = $user_id;

            $temp_data['role_type'] = $role_type + 1;
            $temp_data['score'] = 0.01;
            $temp_data['nickname'] = $nickname;

            $ret = (new Auth())->register($mobile, "123456", '', $mobile, $temp_data);
            if ($ret) {
                $this->success("操作成功");
            } else {
                $this->error("添加失败");
            }
        }
        return $this->view->fetch();
    }

    private function setSepTeamUser($userId, $user_flags)
    {
        $user = Db::table('share_user')->where(['user_id' => $userId])->find();
        $puserlist = Db::table('share_user')->where(['role_url' => ['like', "%" . '/' . $userId . $user['role_url'] . "%"]])->order('id DESC')->select();

        $arr = [['user_id' => $userId,
            'user_flags' => $user_flags,
            'addtime' => time()]];
        foreach ($puserlist as $vv) {
            $info = \db('share_user_flags')->where('user_id', $vv['user_id'])->find();
            if (!$info) {
                array_push($arr, [
                    'user_id' => $vv['user_id'],
                    'user_flags' => $user_flags,
                    'addtime' => time()
                ]);
            }
        }

        if (count($arr) > 0) {
//            \think\log::error(json_encode($arr));
            return Db::name("share_user_flags")->insertAll($arr);
        }
        return false;
    }

    private function getSepTeamUser($userId)
    {
        //$user =(new ShareUser())->get(['user_id'=>$this->user_id]); // 分销用户
        //$puser =(new ShareUser())->get(['user_id'=>$user->parent_id]);

        $teamlist = Db::table('share_user')->where(['is_sep_income' => 1])->select();
        $teamUidArr = [];
        $noteamUidArr = [];
        if (!empty($teamlist)) {
            foreach ($teamlist as $val) {
                $puserlist = Db::table('share_user')->where(['role_url' => ['like', "%" . $val['user_id'] . "%"]])->order('id DESC')->select();
                $userIdsStr = '';
                foreach ($puserlist as $vv) {
                    $userIdsStr = $userIdsStr . $val['role_url'] . '/' . $vv['user_id'];
                }

//                foreach($puserlist as $vl) {
                $userArray = explode('/', $userIdsStr);
                $teamArray = array_filter($userArray);
                $teamArray = array_merge($teamArray, [$val['user_id']]);
                //$isSepIncome = Db::table('share_user')->where(['user_id'=>['IN', $teamArray], 'is_sep_income'=>1])->count();
                if (in_array($userId, $teamArray)) {
                    foreach ($teamArray as $k => $uid) {
                        if ($uid >= $val['user_id']) {
                            $teamUidArr[$k] = $uid;
                        } else {
                            $noteamUidArr[$k] = $uid;
                        }
                    }
                    break;
                }
//                }
            }
        }
        $teamUidArr = array_unique($teamUidArr);
        $noteamUidArr = array_unique($noteamUidArr);
        return ['team_user' => $teamUidArr, 'noteam_user' => $noteamUidArr];
    }

    public function userdel($ids = null)
    {

        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $da = Db::name("user_id_card")->where(['user_id'=>$row['user_id']])->find();
        if(!$da){
            $this->error("此用户没有实名，不用删除");
        }
        $res = Db::name("user_id_card")->where(['user_id'=>$row['user_id']])->delete();
        if ($res) {
            $this->error(__("删除成功"));
        } else {
            $this->error(__("删除失败"));
        }
    }
}
